//
//  statisticalViewController.m
//  ZYShang
//
//  Created by wangguangming on 15/8/11.
//  Copyright © 2015年 Amber. All rights reserved.
//

#import "statisticalViewController.h"
#import "Base.h"
#import "UserModel.h"
#import "Loadsingle.h"
#import "ReadyDiSignle.h"
#import "School.h"
/*
 统计
 **/

@interface statisticalViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *mainTable;
    
    int _intday;
    BOOL _shit;
    BOOL _timeIsShit;
    
    int tableType;
    int timeType;
    NSString *mktidString;
    
    NSString *uidString;
    
    UIScrollView *scroller;
}
@property(nonatomic,strong)UIDatePicker *dataPiker;
@property(nonatomic,strong)UIButton *schoolButton;
@property(nonatomic,strong)UIButton *peopleButton;
@property(nonatomic,strong)UIButton *baginButton;
@property(nonatomic,strong)UIButton *endButton;
@property(nonatomic,strong)UIButton *timeButton;
@property(nonatomic,strong)UIButton *searchButton;


@end

@implementation statisticalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBack];
    self.view.backgroundColor=[UIColor whiteColor];
    self.title=@"统计";
        
    [self buju];
    
    
    // Do any additional setup after loading the view.
}
-(void)buju
{
    _shit=NO;
    _timeIsShit=NO;
    UserModel *user= [Loadsingle single].userArray[0];
    self.schoolButton=[[UIButton alloc] initWithFrame:CGRectMake(5, 69, WIDTH/2-10, 50)];
    
   
   
     
    
    self.peopleButton=[[UIButton alloc] initWithFrame:CGRectMake(WIDTH/2+5, 69, WIDTH/2-10, 50)];
    if(user.role.intValue==1)
        {
    [self.schoolButton setTitle:@"全部" forState:UIControlStateNormal];
     [self.peopleButton setTitle:@"全部" forState:UIControlStateNormal];
        }
    else if(user.role.intValue==2)
        {
        [self.schoolButton setTitle:user.mktName forState:UIControlStateNormal];
        [self.peopleButton setTitle:@"全部" forState:UIControlStateNormal];
        }

    else
        {
         [self.schoolButton setTitle:user.mktName forState:UIControlStateNormal];
        [self.peopleButton setTitle:user.name forState:UIControlStateNormal];
        }
    
   
    [self.schoolButton.titleLabel setAdjustsFontSizeToFitWidth:YES];
    self.schoolButton.backgroundColor=[UIColor grayColor];
    self.peopleButton.backgroundColor=[UIColor grayColor];
   
    [self.view addSubview:self.schoolButton];
    [self.view addSubview:self.peopleButton];
    NSArray *array=@[@"当天",@"当周",@"当月",@"当年"];
    for (int i=0; i<4; i++)
        {
         self.timeButton=[[UIButton alloc] initWithFrame:CGRectMake(5+WIDTH/4*i, 129, 30, 30)];
         UILabel *laber=[[UILabel alloc] initWithFrame:CGRectMake(35+WIDTH/4*i, 124, WIDTH/4-25, 40)];
          
        self.timeButton.backgroundColor=[UIColor grayColor];
        laber.text=array[i];
        [self.timeButton setTag:110+i]; 
        self.timeButton.layer.cornerRadius=15;
        [self.view addSubview:self.timeButton];
        [self.view addSubview:laber];
        [self.timeButton addTarget:self action:@selector(shitAction:) forControlEvents:UIControlEventTouchUpInside];
        }
   
    self.baginButton=[[UIButton alloc] initWithFrame:CGRectMake(5, 170, WIDTH/2-10, 50)];
    
    self.endButton=[[UIButton alloc] initWithFrame:CGRectMake(WIDTH/2+5, 170, WIDTH/2-10, 50)];
    
    
    
    self.baginButton.backgroundColor=[UIColor grayColor];
    self.endButton.backgroundColor=[UIColor grayColor];
    
    [self.baginButton addTarget:self action:@selector(timeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.endButton addTarget:self action:@selector(timeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.schoolButton addTarget:self action:@selector(chooseAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.peopleButton addTarget:self action:@selector(chooseAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    [self.view addSubview:self.baginButton];
    [self.view addSubview:self.endButton];
    
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
    NSDateFormatter *dataformate=[[NSDateFormatter alloc] init];
    [dataformate setDateFormat:@"yyyy-MM-dd"];
    NSString *string=[dataformate stringFromDate:date];

    [self.baginButton setTitle:string forState:UIControlStateNormal];
    [self.endButton setTitle:string forState:UIControlStateNormal];
        //[self addserach];
    
   }
-(void)addserach
{  
    [self.searchButton removeFromSuperview];
    self.searchButton=[[UIButton alloc] initWithFrame:CGRectMake(WIDTH*3/8, CGRectGetMaxY(self.baginButton.frame)+5, WIDTH/4, 40)];
    [self.searchButton addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.searchButton setTitle:@"查询" forState:UIControlStateNormal];
    self.searchButton.backgroundColor=[UIColor redColor];
    [self.view addSubview:self.searchButton];
    

}
-(void)changgeAction:(UIDatePicker*)sender
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd "];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: sender.date];
    
    if (timeType==1)
        {
        [self.baginButton setTitle:currentDateStr forState:UIControlStateNormal];
      }
    else
        {
        [self.endButton setTitle:currentDateStr forState:UIControlStateNormal];
        }
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)shitAction:(UIButton *)sender
{
    if(self.dataPiker)
        {
        [self.dataPiker removeFromSuperview];
        }
    else
        {
        
        }
    
    [scroller removeFromSuperview];
    [self addserach];
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
    NSDateFormatter *dataformate=[[NSDateFormatter alloc] init];
    [dataformate setDateFormat:@"EEEE"];
     NSString *string=[dataformate stringFromDate:date];
    
    
    if ([string isEqualToString:@"星期一"])
        {
        _intday=0;
        }
    else if ([string isEqualToString:@"星期二"])
        {
        _intday=1;
        }
    else if ([string isEqualToString:@"星期三"])
        {
        _intday=2;
        }
    else if ([string isEqualToString:@"星期四"])
            {
            _intday=3;
            }
    else if ([string isEqualToString:@"星期五"])
        {
        _intday=4;
        }
    else if ([string isEqualToString:@"星期六"])
        {
        _intday=5;
        }
    else if ([string isEqualToString:@"星期日"])
        {
        _intday=6;
        }
       
    for (int i=0; i<4; i++)
        {
        UIButton *button=(UIButton *)[self.view viewWithTag:110+i];
        if (sender.tag==110+i) 
            {
            button.backgroundColor=[UIColor blueColor];
            }
        else
            {
            button.backgroundColor=[UIColor grayColor];
            }
        
        
        }
    
    
     if(sender.tag==110)
         {
         NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
         NSDateFormatter *dataformate=[[NSDateFormatter alloc] init];
         [dataformate setDateFormat:@"yyyy-MM-dd"];
         NSString *string=[dataformate stringFromDate:date];

         [self.baginButton setTitle:string forState:UIControlStateNormal];
         [self.endButton setTitle:string forState:UIControlStateNormal];
         
        }
    else if(sender.tag==111)
        {
        NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
        NSDateFormatter *dataformate=[[NSDateFormatter alloc] init];
        [dataformate setDateFormat:@"yyyy-MM-dd"];
        NSString *string=[dataformate stringFromDate:date];
        
       [self.endButton setTitle:string forState:UIControlStateNormal];
        
        NSDate *date1=[NSDate dateWithTimeIntervalSinceNow:-24*3600*_intday];
        NSDateFormatter *dataformate1=[[NSDateFormatter alloc] init];
        [dataformate1 setDateFormat:@"yyyy-MM-dd"];
        NSString *string1=[dataformate1 stringFromDate:date1];
        
        [self.baginButton setTitle:string1 forState:UIControlStateNormal];
         }
    else if(sender.tag==112)
        {
        NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
        NSDateFormatter *dataformate=[[NSDateFormatter alloc] init];
        [dataformate setDateFormat:@"yyyy-MM-dd"];
        NSString *string=[dataformate stringFromDate:date];
        [self.endButton setTitle:string forState:UIControlStateNormal];
        
        NSString *string2=[string substringFromIndex:string.length-2]; 
        
               
        NSDate *date1=[NSDate dateWithTimeIntervalSinceNow:-24*3600*(string2.intValue-1)];
        NSDateFormatter *dataformate1=[[NSDateFormatter alloc] init];
        [dataformate1 setDateFormat:@"yyyy-MM-dd"];
        NSString *string1=[dataformate1 stringFromDate:date1];
        
        [self.baginButton setTitle:string1 forState:UIControlStateNormal];
        }
    else if(sender.tag==113)
        {
        NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
        NSDateFormatter *dataformate=[[NSDateFormatter alloc] init];
        [dataformate setDateFormat:@"yyyy-MM-dd"];
        NSString *string=[dataformate stringFromDate:date];
        [self.endButton setTitle:string forState:UIControlStateNormal];
        
        NSString *string2=[string substringToIndex:4]; 
        
        
        NSString *string1=[NSString stringWithFormat:@"%@-01-01",string2];
        
        [self.baginButton setTitle:string1 forState:UIControlStateNormal];
        

    }
}
-(void)chooseAction:(UIButton *)sender
{
     UserModel *user= [Loadsingle single].userArray[0];
    if (sender== self.schoolButton) 
        {
        if (user.role.intValue==1)
            {
            [[ReadyDiSignle signle] allSchool];
            [[ReadyDiSignle signle] addObserver:self forKeyPath:@"schoolArray" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
            
            tableType=1;
            if (_shit)
                {
                [mainTable removeFromSuperview];
                _shit=NO;
                }
            else
                {
                [mainTable removeFromSuperview];
                mainTable=[[UITableView alloc] initWithFrame:CGRectMake(CGRectGetMinX(sender.frame), CGRectGetMaxY(sender.frame)+2, CGRectGetWidth(sender.frame), 200)];
                [self.view addSubview:mainTable];
                mainTable.delegate=self;
                mainTable.dataSource=self;
                _shit=YES;
                }


          }
        else
            {
            
            
            }
    }
    else
        {
        if (mktidString==nil)
            {
            
            [[ReadyDiSignle signle] allWorkers];
            [[ReadyDiSignle signle] addObserver:self forKeyPath:@"workerArray" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
                      }
        else
            {
                //  NSLog(@"%@",mktidString);
            [ReadyDiSignle signle].oidString=mktidString;
            [[ReadyDiSignle signle] getAllwokers];
            [[ReadyDiSignle signle] addObserver:self forKeyPath:@"workerArray" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
            }
        tableType=2;
        if (_shit)
            {
            [mainTable removeFromSuperview];
            _shit=NO;
            }
        else
            {
            [mainTable removeFromSuperview];
            mainTable=[[UITableView alloc] initWithFrame:CGRectMake(CGRectGetMinX(sender.frame), CGRectGetMaxY(sender.frame)+2, CGRectGetWidth(sender.frame), 200)];
            [self.view addSubview:mainTable];
            mainTable.delegate=self;
            mainTable.dataSource=self;
            _shit=YES;
            }

        }

    
  
       
}
-(void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary *)change context:(nullable void *)context
{
    if ([keyPath isEqualToString:@"schoolArray"]) 
        {
        [mainTable reloadData];
        
        [[ReadyDiSignle signle] removeObserver:self forKeyPath:@"schoolArray"];
        }
    else if ([keyPath isEqualToString:@"workerArray"]) 
        {
        [mainTable reloadData];
        
        [[ReadyDiSignle signle] removeObserver:self forKeyPath:@"workerArray"];
        }
    else if ([keyPath isEqualToString:@"resultDict"]) 
        {
        [mainTable reloadData];
        
        [[ReadyDiSignle signle] removeObserver:self forKeyPath:@"resultDict"];
        [self resultitems];        
        }


}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableType==1) 
        {
        return [ReadyDiSignle signle].schoolArray.count+1;
        }
    else
        {
    return [ReadyDiSignle signle].workerArray.count+1;
        }
}

  
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *cellid=@"statistcellid";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell==nil)
        {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
        }
    cell.backgroundColor=[UIColor grayColor];
    
    if (tableType==1)
        {
        if (indexPath.row==0) 
            {
            cell.textLabel.text=@"全部";
            }
        else
            {
        School *school=[ReadyDiSignle signle].schoolArray[indexPath.row-1];
        cell.textLabel.text=school.name;
            }
        }
    else
    {
    if (indexPath.row==0) 
        {
        cell.textLabel.text=@"全部";
        }
    else
       {
       UserModel *user=[ReadyDiSignle signle].workerArray[indexPath.row-1];
       cell.textLabel.text=user.name;
       }
    }
    
    return cell;
}
-(void)tableView:(nonnull UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
   if(tableType==1)
       {
       if (indexPath.row==0)
           {
           [self.schoolButton setTitle:@"全部" forState:UIControlStateNormal];
           mktidString=nil;
          }
       else
           {
           School *school=[ReadyDiSignle signle].schoolArray[indexPath.row-1];
           
           mktidString=school.mktId;
           [self.schoolButton setTitle:school.name forState:UIControlStateNormal];
            [self.peopleButton setTitle:@"全部" forState:UIControlStateNormal];
           }
       }
    else
        {
        if (indexPath.row==0)
            {
            [self.peopleButton setTitle:@"全部" forState:UIControlStateNormal];
            uidString=nil;
            }
        else
            {
           UserModel *user=[ReadyDiSignle signle].workerArray[indexPath.row-1];
            
            uidString=user._id;
            [self.peopleButton setTitle:user.name forState:UIControlStateNormal];
            }

        
        }
    [mainTable removeFromSuperview];
}

-(void)timeAction:(UIButton *)sender
{
    [scroller removeFromSuperview];
    
    if (!_timeIsShit) {
        [self.searchButton removeFromSuperview];
    [self.dataPiker removeFromSuperview];
    self.dataPiker=[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 220, WIDTH, HEIGHT/2)];
    self.dataPiker.datePickerMode=UIDatePickerModeDate;
    [self.view addSubview:self.dataPiker];
    [self.dataPiker addTarget:self action:@selector(changgeAction:) forControlEvents:UIControlEventValueChanged];
    NSLocale *locale=[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    self.dataPiker.locale=locale;
    
    
    
    NSDate *pickDate=[self.dataPiker date];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: pickDate];
    
   
        
        _timeIsShit=YES;
    }
    else
        {
        [self addserach];
        [self.dataPiker removeFromSuperview];
       _timeIsShit=NO;
        }
    if (sender==self.baginButton) 
        {
        timeType=1;
       }
    else
        {
        timeType=2;
        }
}
-(void)searchAction:(UIButton *)sender
{
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[date timeIntervalSince1970]*1000;
       
    NSDateFormatter *dataformate=[[NSDateFormatter alloc] init];
    [dataformate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *string=[dataformate stringFromDate:date];
    NSString *beginstring=[NSString stringWithFormat:@"%@ 00:00:00",self.baginButton.titleLabel.text];
    NSString *endstring=[NSString stringWithFormat:@"%@ 23:59:59",self.endButton.titleLabel.text];
        // NSLog(@"b=====%@  e===%@  ",beginstring,endstring);
    
    long double begingTime =[self setString:beginstring];
    long double endTime=  [self setString:endstring];
    
    [[ReadyDiSignle signle] searchallMktid:mktidString Uid:uidString From:begingTime to:endTime];
     
        //[ReadyDiSignle signle].resultDict;
    
    [[ReadyDiSignle signle] addObserver:self forKeyPath:@"resultDict" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    
}
-(long double)setString:(NSString *)string
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;  
    [formatter setDateStyle:NSDateFormatterMediumStyle];  
    [formatter setTimeStyle:NSDateFormatterShortStyle];     
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制  
    
        //设置时区,这个对于时间的处理有时很重要  
        //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.  
        //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?  
        //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了  
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];  
    [formatter setTimeZone:timeZone];  
    
    NSDate* date = [formatter dateFromString:string]; //------------将字符串按formatter转成nsdate  
     
        //NSLog(@"timeSp:%@",timeSp); //时间戳的值  
        //NSLog(@"%f",[date timeIntervalSince1970]*1000);
    return [date timeIntervalSince1970]*1000;
    
}
-(void)resultitems
{
    [self.searchButton removeFromSuperview];
    
    scroller=[[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.baginButton.frame)+5, WIDTH, HEIGHT-CGRectGetMaxY(self.baginButton.frame)+5)];
    [self.view addSubview:scroller];
    
    NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithDictionary:[ReadyDiSignle signle].resultDict];
    for (int i=0; i<[dict allKeys].count ;i++) 
        {
        UILabel *namelaber=[[UILabel alloc] initWithFrame:CGRectMake(0, 0+45*i, WIDTH,40)];
        namelaber.text=[NSString stringWithFormat:@"%@:%@",[dict allKeys][i],[dict allValues][i]];
        [namelaber setAdjustsFontSizeToFitWidth:YES];
        [scroller addSubview:namelaber];
        }
    scroller.contentSize=CGSizeMake(0, 45*[dict allKeys].count );
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
